# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.conf import settings
from django.core.paginator import Paginator, EmptyPage
from django.db.models import Q
from django.http import JsonResponse
from django.shortcuts import render
from django import http
# Create your views here.
from django.views import View
import json
from apps.homes.models import Area, House, HouseImage, Facility
from apps.homes.models import Order
from ihome_team7.libs.qiniuyun.qiniuyun_upload import storage
import datetime


class AuthView(View):
    def get(self, request):
        return http.JsonResponse({'errno': 0})


class AreaView(View):
    def get(self, request):
        # 获取Area查询集
        areas = Area.objects.all()

        data = []

        for area in areas:
            area_dict = {}
            area_dict['aid'] = area.id
            area_dict['aname'] = area.name
            data.append(area_dict)

        return http.JsonResponse({'errno': '0', 'errmsg': '获取成功', 'data': data})


# 未完成
class LaunchSearchView(View):
    def post(self, request):
        request_dict = json.loads(request.body.decode())
        user = request.user
        # 提取参数
        title = request_dict.get('title')
        price = request_dict.get('price')
        address = request_dict.get('address')
        area_id = request_dict.get('area_id')
        room_count = request_dict.get('room_count')
        acreage = request_dict.get('acreage')
        unit = request_dict.get('unit')
        capacity = request_dict.get('capacity')
        beds = request_dict.get('beds')
        deposit = request_dict.get('deposit')
        min_days = request_dict.get('min_days')
        max_days = request_dict.get('max_days')
        facilities = request_dict.get('facility')

        if not all([title, price, address, area_id, room_count, acreage, unit, capacity, beds, deposit, min_days,
                    max_days]):
            return http.JsonResponse({"errno": "400",
                                      "errmsg": "信息不完整"})

        # 保存房屋信息
        try:
            house = House.objects.create(
                area_id=area_id,
                user=user,
                title=title,
                price=price,
                address=address,
                room_count=room_count,
                acreage=acreage,
                unit=unit,
                capacity=capacity,
                beds=beds,
                deposit=deposit,
                min_days=min_days,
                max_days=max_days

            )

        except Exception as e:
            return http.JsonResponse({"errno": "400",
                                      "errmsg": "房屋发布失败"})
        # 保存设施信息
        facilities = Facility.objects.filter(id__in=facilities)
        if facilities:
            for facility in facilities:
                house.facility.add(facility)

        return http.JsonResponse({"errno": 0, "errmsg": "发布成功", "data": {'house_id': house.id}})

    def get(self, request):
        # 接收参数
        aid = request.GET.get("aid")
        start_day = request.GET.get("sd")
        end_day = request.GET.get("ed")
        sort_key = request.GET.get("sk")
        page = request.GET.get("p", 1)
        # 校验参数
        if not all([aid, start_day, end_day, sort_key, page]):
            return http.JsonResponse({"errno": 4103, "errmsg": "缺少必传参数"})
        try:
            area = Area.objects.get(id=aid)
        except Area.DoesNotExist:
            return http.JsonResponse({"errno": 4002, "errmsg": "参数aid有误"})
        try:
            page_num = int(page)
        except Exception as e:
            return http.JsonResponse({"errno": 4002, "errmsg": "参数page有误"})

            # 核心逻辑
        # 居住天数
        start_day = datetime.datetime.strptime(start_day, '%Y-%m-%d')
        end_day = datetime.datetime.strptime(end_day, '%Y-%m-%d')
        if start_day > end_day:
            return http.JsonResponse({"errno": 4103, "errmsg": "参数sd或ed有误"})

        duration = (end_day - start_day).days
        if sort_key == "new":
            sort = "-create_time"
        elif sort_key == "booking":
            sort = "order_count"
        elif sort_key == "price-inc":
            sort = "price"
        elif sort_key == "price-des":
            sort = "-price"

        # 查询已有订单可能日期冲突的房屋
        try:
            conflict_orders = Order.objects.filter(
                Q(begin_date__gt=start_day, begin_date__lt=end_day) | Q(begin_date__lt=start_day,
                                                                        end_date__gt=start_day))
        except House.DoesNotExist:
            return JsonResponse({'code': 400, 'errmsg': '获取mysql数据出错'})

        conflict_house_ids = [order.house.id for order in conflict_orders]
        filters = {}
        if conflict_house_ids:
            filters["id__in"] = conflict_house_ids
        else:
            filters["id__in"] = []

        try:
            house_model_list = House.objects.exclude(**filters).filter(area=aid, min_days__lte=duration).filter(
                Q(max_days__gte=duration) | Q(max_days__exact=0)).order_by(sort)

            # house_model_list = House.objects.filter(Q(max_days__gte=duration)|Q(max_days__exact=0)).order_by(sort)
        except House.DoesNotExist:
            return JsonResponse({'code': 400, 'errmsg': '获取mysql数据出错'})

        # 分页器对象
        paginator = Paginator(house_model_list, 2)
        # 获取每页数据
        try:
            page_houses = paginator.page(page_num)
        except EmptyPage:
            # 如果page_num不正确，默认给用户400
            return JsonResponse({'code': 400, 'errmsg': 'page数据出错'})
        # 获取列表页总页数
        total_page = paginator.num_pages

        houses_list = []
        for house in page_houses:
            houses_list.append({
                "address": house.address,
                "area_name": area.name,
                "ctime": house.create_time,
                "house_id": house.id,
                "img_url": house.index_image_url,
                "order_count": house.order_count,
                "price": house.price,
                "room_count": house.room_count,
                "title": house.title,
                "user_avatar": str(house.user.avatar)
            })
        data = {"houses": houses_list, "total_page": total_page}

        # 响应参数
        return http.JsonResponse({"errno": 0, "errmsg": "ok", "data": data})


class ImageHouseView(View):

    def post(self, request, house_id):
        # 读取拼接链接
        file = request.FILES.get('house_image')
        img = file.read()
        if not img:
            return http.JsonResponse({"errno": "400",
                                      "errmsg": "图片上传失败"})

        img_url = settings.QNY_HOST + storage(img)

        # 保存到对应的房间对象
        house = House.objects.get(pk=house_id)
        house.index_image_url = img_url
        house.save()

        return http.JsonResponse({"data": {
            "url": img_url
        },
            "errno": "0",
            "errmsg": "图片上传成功"})


class HouselistView(View):
    '''
    当前用户房屋列表
    '''

    def get(self, request):
        # 先构建字典和列表
        data_dict = {}
        house_list = []

        if not request.user.is_authenticated:
            return http.JsonResponse({"errmsg": "没登录",
                                      "errno": "400", })
        # 再取当前用户id
        user_id = request.user.id

        # 取出对应房屋信息表 对象

        house_infos = House.objects.filter(user_id=user_id,is_deleted=False)

        for house in house_infos:
            house_list.append({
                "address": house.address,
                "area_name": house.area.name,
                "ctime": str(house.create_time),
                "house_id": house.id,
                "img_url": str(house.index_image_url),
                "order_count": house.order_count,
                "price": house.price,
                "room_count": house.room_count,
                "title": house.title,
                "user_avatar": str(request.user.avatar)

            })

        data_dict['houses'] = house_list

        return http.JsonResponse({"errmsg": "ok",
                                  "errno": "0", 'data': data_dict
                                  })


class HouseIndexView(View):

    def get(self, request):
        # 获取所有房屋信息
        houses = House.objects.all()[:5]

        house_list = []
        for house in houses:
            house_list.append({
                "house_id": house.id,
                "img_url": house.index_image_url,
                "title": house.title

            })

        return http.JsonResponse({"errmsg": "OK",
                                  "errno": "0",
                                  "data": house_list})


class HousedetailView(View):

    def get(self, request, house_id):

        if not request.user.is_authenticated:
            return http.HttpResponseRedirect('http://127.0.0.1:8080/index.html')

        # 取出选中的house_id房屋对象

        house_obj = House.objects.get(pk=house_id)

        # 取出对应order对象

        order_obj = house_obj.order_set.all()

        # 构建评论列表
        comments = []

        for order in order_obj:
            # 取出当前订单的用户对象
            user = order.user
            comments.append({
                'comment': order.comment,
                "ctime": order.create_time,
                'user_name': user.username,
            })

        # 构建设施列表

        facilities = []
        # 取出对应设施对象
        facility_list = house_obj.facility.all()
        for facility in facility_list:
            facilities.append(facility.id)

        # 构建房屋图片对象图片列表
        img_list = []
        imgs_house = HouseImage.objects.filter(house=house_obj)
        for img in imgs_house:
            img_list.append(img.url)

        # 当前房屋所有者
        owner = house_obj.user
        # 加入
        if not order_obj:
            comments = [{
                "comment": "哎哟不错哟",
                "ctime": "2017-11-14 11:17:07",
                "user_name": "匿名用户"
            }]
        house = {
            "acreage": house_obj.acreage,
            "address": house_obj.address,
            "beds": house_obj.beds,
            "capacity": house_obj.capacity,
            "comments": comments,
            "deposit": house_obj.deposit,
            "facilities": facilities,
            "hid": house_obj.id,
            "img_urls": img_list,
            "max_days": house_obj.max_days,
            "min_days": house_obj.min_days,
            "price": float(house_obj.price),
            "room_count": house_obj.room_count,
            "title": house_obj.title,
            "unit": house_obj.unit,
            "user_avatar": str(owner.avatar),
            "user_id": owner.id,
            "user_name": owner.username
        }

        # 判断是否登录
        if not request.user.is_authenticated:
            user_id = -1
        else:
            user_id = request.user.id
        data = {
            'house': house,
            "user_id": user_id,

        }

        return http.JsonResponse({'data': data, "errmsg": "OK",
                                  "errno": "0"})

class HousedeleteView(View):
    def put(self,request,house_id):
        try:
            house = House.objects.get(id=house_id)
            house.is_deleted = True
            house.save()
        except Exception as e:
            return http.JsonResponse({'errno': 400, "errmsg": "删除失败"})
        return http.JsonResponse({'errno': 0, "errmsg": "ok"})


